﻿' ******************************************************************************
' ** 
' **  Yahoo! Managed
' **  Written by Marius Häusler 2011
' **  It would be pleasant, if you contact me when you are using this code.
' **  Contact: YahooFinanceManaged@gmail.com
' **  Project Home: http://code.google.com/p/yahoo-finance-managed/
' **  
' ******************************************************************************
' **  
' **  Copyright 2011 Marius Häusler
' **  
' **  Licensed under the Apache License, Version 2.0 (the "License");
' **  you may not use this file except in compliance with the License.
' **  You may obtain a copy of the License at
' **  
' **    http://www.apache.org/licenses/LICENSE-2.0
' **  
' **  Unless required by applicable law or agreed to in writing, software
' **  distributed under the License is distributed on an "AS IS" BASIS,
' **  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
' **  See the License for the specific language governing permissions and
' **  limitations under the License.
' ** 
' ******************************************************************************


Namespace YahooManaged


    Friend Class MyHelper

        Public Function StreamToString(ByVal stream As IO.Stream, ByVal encoding As System.Text.Encoding) As String
            Dim res As String = String.Empty
            If stream IsNot Nothing Then
                Dim enc As System.Text.Encoding = encoding
                If enc Is Nothing Then enc = System.Text.Encoding.UTF8
                Using sr As New IO.StreamReader(stream, enc)
                    res = sr.ReadToEnd
                End Using
            End If
            Return res
        End Function
        Public Function StreamToBytes(ByVal s As IO.Stream) As Byte()
            Dim result As Byte() = New Byte() {}
            If s IsNot Nothing Then
                result = New Byte(CInt(s.Length)) {}
                s.Read(result, 0, CInt(s.Length))
            End If
            Return result
        End Function
        Public Sub CloseStream(ByVal s As IO.Stream)
            If s IsNot Nothing Then
                s.Flush()
                s.Close()
                s.Dispose()
            End If
        End Sub
        Public Function EnumToArray(Of T)(ByVal values As IEnumerable(Of T)) As T()
            If values IsNot Nothing Then
                If TypeOf values Is T() Then : Return DirectCast(values, T())
                Else : Return New List(Of T)(values).ToArray
                End If
            Else : Return New T() {}
            End If
        End Function
        Public Function CharEnumToString(ByVal arr As IEnumerable(Of Char)) As String
            Dim s As String = String.Empty
            If arr IsNot Nothing Then
                For Each c As Char In arr
                    s &= c
                Next
            End If
            Return s
        End Function
        Public Function StringToObject(ByVal str As String, ByVal ci As Globalization.CultureInfo) As Object
            Dim value As String = str.Replace("%", "").Replace("""", "").Trim
            If value <> String.Empty Then
                If value.Contains(" - ") Then
                    Dim values = value.Split(New String() {" - "}, StringSplitOptions.None)
                    Dim results As New List(Of Object)
                    For Each v In values
                        results.Add(Me.StringToObject(v, ci))
                    Next
                    Return results.ToArray
                Else
                    Dim dbl As Double
                    If Double.TryParse(value, Globalization.NumberStyles.Any, ci, dbl) Then
                        Return dbl
                    Else
                        Dim lng As Long
                        If Long.TryParse(value, lng) Then
                            Return lng
                        Else
                            Dim dte As Date
                            If Date.TryParse(value, ci, Globalization.DateTimeStyles.AdjustToUniversal, dte) Then
                                Return dte
                            Else
                                If value = "N/A" Then : Return String.Empty
                                Else : Return value
                                End If
                            End If
                        End If
                    End If
                End If
            Else
                Return value
            End If
        End Function
        Public Function ObjectToString(ByVal value As Object, ByVal ci As Globalization.CultureInfo) As String
            If value IsNot Nothing Then
                If TypeOf value Is Double Then : Return Convert.ToDouble(value).ToString(ci)
                ElseIf TypeOf value Is Date Then : Return Convert.ToDateTime(value).ToString(ci)
                ElseIf TypeOf value Is Object() Then
                    Dim values() As Object = CType(value, Object())
                    Dim sb As New Text.StringBuilder
                    For Each obj In values
                        sb.Append(Me.ObjectToString(obj, ci))
                        If obj IsNot values(values.Length - 1) Then sb.Append(" - ")
                    Next
                    Return sb.ToString
                Else : Return value.ToString
                End If
            Else : Return String.Empty
            End If
        End Function

        Public Function GetXmlDocument(ByVal xml As IO.Stream) As XmlDocument
            If xml IsNot Nothing AndAlso xml.CanRead Then
                Try
                    Dim xmlDoc As New XmlDocument
                    xmlDoc.Load(xml)
                    Return xmlDoc
                Catch ex As Exception
                    Return Nothing
                End Try
            Else
                Return Nothing
            End If
        End Function

        Public Function GetResultsFromXml(ByVal xml As IO.Stream, ByVal nodeName As String) As XmlNode()
            Dim res(-1) As XmlNode
            Dim xmlDoc = Me.GetXmlDocument(xml)
            If xmlDoc IsNot Nothing Then
                Dim lst = xmlDoc.GetElementsByTagName(nodeName)
                Dim arr(lst.Count - 1) As XmlNode
                If lst.Count > 0 Then
                    For i As Integer = 0 To lst.Count - 1
                        arr(i) = lst(i)
                    Next
                End If
                res = arr
            End If
            Me.CloseStream(xml)
            Return res
        End Function
        Public Function GetXmlAttributeValue(ByVal node As XmlNode, ByVal attName As String) As String
            If node IsNot Nothing Then
                Dim att = node.Attributes(attName)
                If att IsNot Nothing AndAlso att.InnerText <> String.Empty Then
                    Return att.InnerText
                End If
            End If
            Return String.Empty
        End Function

        Public Function CultureToParameters(ByVal cult As Culture) As String
            If cult Is Nothing Then Throw New ArgumentNullException("cult", "Culture must have a value")
            Return String.Format("&region={0}&lang={1}-{2}", cult.Country.ToString, cult.Language.ToString, cult.Country.ToString)
        End Function


        Public Function YqlUrl(ByVal statement As String, ByVal json As Boolean) As String
            Dim format As String = "json"
            If json = False Then format = "xml"
            Return "http://query.yahooapis.com/v1/public/yql?q=" & Uri.EscapeDataString(statement) & "&format=" & format & "&diagnostics=false&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys"
        End Function
        Public Function YqlUrl(ByVal fields As String, ByVal table As String, ByVal whereParam As String, ByVal opt As ResultCountOptions, ByVal json As Boolean) As String
            Return Me.YqlUrl(Me.YqlStatement(fields, table, whereParam, opt), json)
        End Function
        Public Function YqlStatement(ByVal fields As String, ByVal table As String, ByVal whereParam As String, ByVal opt As ResultCountOptions) As String
            Dim stmt As New Text.StringBuilder
            stmt.Append("select ")
            stmt.Append(fields)
            stmt.Append(" from ")
            stmt.Append(table)
            If opt IsNot Nothing AndAlso opt.Count > 0 Then
                stmt.Append("(")
                stmt.Append(opt.Start.ToString)
                stmt.Append(",")
                stmt.Append(opt.Count.ToString)
                stmt.Append(")")
            End If
            If whereParam.Trim <> String.Empty Then
                stmt.Append(" where ")
                stmt.Append(whereParam)
            End If
            Return stmt.ToString
        End Function
        Public Function CleanYqlParam(ByVal id As String) As String
            Return id.Replace("""", "").Replace("'", "").Trim
        End Function

        Public Function ServerString(ByVal server As Server) As String
            Select Case server
                Case server.Argentina : Return "ar."
                Case server.Australia : Return "au."
                Case server.Brazil : Return "br."
                Case server.Canada : Return "ca."
                Case server.France : Return "fr."
                Case server.Germany : Return "de."
                Case server.HongKong : Return "hk."
                Case server.India : Return "in."
                Case server.Italy : Return "it."
                Case server.Korea : Return "kr."
                Case server.Mexico : Return "mx."
                Case server.Singapore : Return "sg."
                Case server.Spain : Return "es."
                Case server.UK : Return "uk."
                Case YahooManaged.Server.NewZealand : Return "nz."
                Case Else : Return String.Empty
            End Select
        End Function

        Public Function CsvTextToStringTable(ByVal csv As String, ByVal delimiter As Char) As String()()
            Dim rows() As String = csv.Split(Microsoft.VisualBasic.ChrW(10))
            Dim lst As New List(Of String())
            For Each row As String In rows
                If row.Trim <> String.Empty Then lst.Add(Me.CsvRowToStringArray(row.Trim, delimiter))
            Next
            Return lst.ToArray
        End Function

        Public Function CsvRowToStringArray(ByVal row As String, ByVal delimiter As Char, Optional ByVal withQuoteMarks As Boolean = True) As String()
            If withQuoteMarks Then
                Dim lstParts As New List(Of String)
                Dim actualIndex As Integer = 0
                Dim tempStartIndex As Integer = 0
                Dim waitForNextQuoteMark As Boolean = False
                Dim actualPartInQuotes As Boolean = False
                Do Until actualIndex = row.Length
                    If row(actualIndex) = """" Then
                        waitForNextQuoteMark = Not waitForNextQuoteMark
                    ElseIf row(actualIndex) = delimiter Then
                        If Not waitForNextQuoteMark Then
                            lstParts.Add(Me.ClearCsvString(row.Substring(tempStartIndex, actualIndex - tempStartIndex)))
                            tempStartIndex = actualIndex + 1
                        End If
                    End If
                    actualIndex += 1
                    If actualIndex = row.Length Then
                        Dim s As String = Me.ClearCsvString(row.Substring(tempStartIndex, actualIndex - tempStartIndex))
                        lstParts.Add(s)
                    End If
                Loop
                Return lstParts.ToArray
            Else
                Return row.Split(delimiter)
            End If
        End Function
        Private Function ClearCsvString(ByVal csv As String) As String
            If csv.Length > 0 Then
                Dim result As String = csv
                If result.StartsWith(""""c) Then result = result.Substring(1)
                If result.EndsWith(""""c) Then result = result.Substring(0, result.Length - 1)
                Return result.Replace("""""", """"c)
            Else : Return csv
            End If
        End Function


    End Class


End Namespace